<!DOCTYPE html>
<html>
<head>
    <title>多线程任务处理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .task-list {
            margin-top: 20px;
        }
        .task-item {
            border: 1px solid #ddd;
            padding: 10px;
            margin: 5px 0;
            border-radius: 4px;
        }
        .running {
            background-color: #fff3cd;
        }
        .completed {
            background-color: #d4edda;
        }
    </style>
</head>
<body>
    <h1>多线程任务处理系统</h1>

    <div>
        <label for="processTime">处理时间（秒）：</label>
        <input type="number" id="processTime" value="5" min="1" max="10">
        <button onclick="submitTask()">提交任务</button>
    </div>

    <div class="task-list" id="taskList">
        <!-- 任务列表将在这里动态显示 -->
    </div>

    <script>
        function submitTask() {
            const processTime = document.getElementById('processTime').value;

            fetch('/submit_task', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    process_time: processTime
                })
            })
            .then(response => response.json())
            .then(data => {
                const taskId = data.task_id;
                addTaskToList(taskId);
                pollTaskStatus(taskId);
            });
        }

        function addTaskToList(taskId) {
            const taskList = document.getElementById('taskList');
            const taskElement = document.createElement('div');
            taskElement.id = `task-${taskId}`;
            taskElement.className = 'task-item running';
            taskElement.innerHTML = `任务 ${taskId}: 正在处理...`;
            taskList.insertBefore(taskElement, taskList.firstChild);
        }

        function pollTaskStatus(taskId) {
            const checkStatus = () => {
                fetch(`/task_status/${taskId}`)
                    .then(response => response.json())
                    .then(data => {
                        const taskElement = document.getElementById(`task-${taskId}`);
                        if (data.status === 'completed') {
                            taskElement.className = 'task-item completed';
                            taskElement.innerHTML = data.result;
                        } else if (data.status === 'running') {
                            setTimeout(checkStatus, 1000);
                        }
                    });
            };

            checkStatus();
        }
    </script>
</body>
</html>
